package com.sec.android.app.myfiles.fragment.settings;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.samsung.android.sdk.slinkcloud.CloudGatewaySignInUtils;
import com.samsung.android.sdk.slinkcloud.CloudGatewayStorageUtils;
import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.dialog.UnableToAccessServerDialogFragment;
import com.sec.android.app.myfiles.dialog.UpdateDialogFragment;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.facade.cmd.SpinnerProgressCmd;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.feature.cloud.AbsCloudImp;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.CloudType;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.OptimizeStorageType;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.update.APKDownloadManager;
import com.sec.android.app.myfiles.update.UpdateChecker;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.UiUtils;

import java.util.Collection;
import java.util.HashMap;

public class SettingsFragment extends AbsSettingsFragment implements CloudMgr.CloudStateListener, UpdateChecker.StubUpdateCheckListener {
    public static final String SIGN_IN_CLOUD_TYPE = "com.sec.android.app.myfiles.SIGN_IN_CLOUD_TYPE";
    private Context mContext;
    private CloudMgr mCloudMgr;
    private CloudType mSelectedCloudType;
    private HashMap<CloudType, View> mAccountViewList = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        mContext = getContext();
        mActivity.setActionBar(R.string.myfiles_settings);
        mActivity.setScreenPath(SamsungAnalyticsLog.ScreenPath.SETTINGS);

        View rootView = inflater.inflate(R.layout.settings_layout, container, false);
        mCloudMgr = CloudMgr.getInstance(mContext);
        mCloudMgr.addListener(this);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        setFileManagementSettings(view);
        setCloudSettings(view);
        ensureOptimizeStorageSettings(view);
    }

    private void ensureOptimizeStorageSettings(View root) {
        if (UiUtils.supportOptimizeStorage(mContext)) {
            View container;
            ViewStub stub = (ViewStub) root.findViewById(R.id.optimize_storage_settings_stub);
            if (stub != null) {
                container = stub.inflate();
            } else {
                container = root.findViewById(R.id.optimize_storage_settings);
            }
            if (container != null) {
                final String size = Formatter.formatShortFileSize(mContext, PreferenceUtils.getLargeFilesSize(mContext));
                setOptimizeStorageSettings(container.findViewById(R.id.settings_large_files),
                        getString(R.string.tmbody_find_files_larger_than), size,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS, SamsungAnalyticsLog.Event.LARGE_FILES, size, null);
                                enterSubPage(OptimizeStorageRangeSettings.getInstance(OptimizeStorageType.LargeFiles), "largeFiles");
                            }
                        });

                int unusedFilesPeriod = PreferenceUtils.getUnusedFilesPeriod(mContext);
                Resources res = mContext.getResources();
                final String strUnusedFilesPeriod = UiUtils.getQuantityString(res, R.plurals.sbody_pd_months, unusedFilesPeriod, unusedFilesPeriod);
                setOptimizeStorageSettings(container.findViewById(R.id.settings_unused_files),
                        getString(R.string.tmbody_find_files_unused_for),
                        strUnusedFilesPeriod,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS, SamsungAnalyticsLog.Event.UNUSED_FILES, strUnusedFilesPeriod, null);
                                enterSubPage(OptimizeStorageRangeSettings.getInstance(OptimizeStorageType.UnusedFiles), "unusedFiles");
                            }
                        });
            }

            if (UiUtils.isTalkBackEnabled(mContext)) {
                TextView optimizeStorageSubTitle = (TextView) root.findViewById(R.id.optimize_storage_subtitle);
                if (optimizeStorageSubTitle != null) {
                    optimizeStorageSubTitle.setContentDescription(UiUtils.getHomeDescription(mContext,
                            R.string.menu_get_more_space, R.string.tts_header));
                }
            }

        }
    }

    private void setOptimizeStorageSettings(View view, String title, String description, View.OnClickListener clickListener) {
        if (view != null) {
            view.setOnClickListener(clickListener);
            TextView titleTextView = (TextView) view.findViewById(R.id.optimize_storage_settings_list_item_text);
            if (titleTextView != null) {
                titleTextView.setText(title);
            }
            TextView descTextView = (TextView) view.findViewById(R.id.optimize_storage_settings_list_item_text_second);
            if (descTextView != null) {
                if (descTextView.getVisibility() != View.VISIBLE) {
                    descTextView.setVisibility(View.VISIBLE);
                }
                descTextView.setText(description);
            }
        }
    }

    private void setCloudSettings(View rootView) {
        if (UiUtils.supportCloudGateway(mContext)) {
            ViewStub cloudAccountListStub = (ViewStub) rootView.findViewById(R.id.cloud_account_list_view_stub);
            if (cloudAccountListStub != null) {
                cloudAccountListStub.inflate();
            }

            if (UiUtils.isTalkBackEnabled(mContext)) {
                TextView cloudSubTitle = (TextView) rootView.findViewById(R.id.cloud_subtitle);
                if (cloudSubTitle != null) {
                    cloudSubTitle.setContentDescription(UiUtils.getHomeDescription(mContext, R.string.cloud_account, R.string.tts_header));
                }
            }
            setCloudAccount(rootView);
            setAccessWiFiOnlySetting(rootView);
        }
    }

    private void setFileManagementSettings(View rootView) {
        setShowHiddenFilesSetting(rootView);
        setShowRecentFilesSetting(rootView);
        setAboutPage(rootView);

        if (UiUtils.isTalkBackEnabled(mContext)) {
            TextView fileManagement = (TextView) rootView.findViewById(R.id.file_management_subtitle);
            if (fileManagement != null) {
                fileManagement.setContentDescription(UiUtils.getHomeDescription(mContext, R.string.settings_file_management, R.string.tts_header));
            }
        }
    }

    private void setShowRecentFilesSetting(View rootView) {
        ViewStub showRecentFilesStub = (ViewStub) rootView.findViewById(R.id.show_recent_files_stub);
        if (showRecentFilesStub != null) {
            showRecentFilesStub.inflate();
        }

        View itemLayout = rootView.findViewById(R.id.show_recent_files_switch_layout);
        if (itemLayout != null) {
            boolean showRecent = PreferenceUtils.getShowRecentFiles(mContext);
            OnCheckedChangeListener listener = new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // SA should be added here
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS, SamsungAnalyticsLog.Event.SHOW_RECENT_FILES,
                            (isChecked) ? "1" : "0", null);
                    MyFilesFacade.setShowRecentFiles(mProcessId, mContext);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            UiUtils.sendLocalBroadcastIntent(mContext, AppConstants.MYFILES_ACTION_SHOW_RECENT_FILES_CHANGED, mProcessId);
                        }
                    }, 100);
                }
            };
            setSwitchView(itemLayout, R.id.show_recent_switch_btn, showRecent, R.string.show_recent_files, R.string.show_recent_files_subtext, listener);
        }
    }

    private void setShowHiddenFilesSetting(View rootView) {
        ViewStub showHiddenFilesStub = (ViewStub) rootView.findViewById(R.id.show_hidden_files_stub);
        if (showHiddenFilesStub != null) {
            showHiddenFilesStub.inflate();
        }

        View itemLayout = rootView.findViewById(R.id.show_hidden_files_switch_layout);
        if (itemLayout != null) {
            boolean bEnable = PreferenceUtils.getShowHiddenFiles(mContext);
            OnCheckedChangeListener listener = new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS, SamsungAnalyticsLog.Event.SHOW_HIDDEN,
                            (isChecked) ? "1" : "0", null);
                    MyFilesFacade.setShowHiddenFiles(mProcessId, mContext, null);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            UiUtils.sendLocalBroadcastIntent(mContext, AppConstants.MYFILES_ACTION_SHOW_HIDDEN_FILES_CHANGED, mProcessId);
                        }
                    }, 100);
                }
            };

            setSwitchView(itemLayout, R.id.show_hidden_switch_btn, bEnable, R.string.menu_show_hidden_files, R.string.show_hidden_files_subtext, listener);
        }
    }

    private void setAccessWiFiOnlySetting(View rootView) {
        ViewStub wifiOnlyStub = (ViewStub) rootView.findViewById(R.id.wifi_only_view_stub);
        if (wifiOnlyStub != null) {
            wifiOnlyStub.inflate();
        }

        View itemLayout = rootView.findViewById(R.id.wifi_switch_layout);
        if (itemLayout != null) {

            final CloudGatewaySignInUtils cloudUtils = CloudGatewaySignInUtils.getInstance(mContext);
            final boolean isWifiOnlyMode = cloudUtils.getWifiOnlyMode();
            OnCheckedChangeListener listener = new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS, SamsungAnalyticsLog.Event.MANAGE_WIFI,
                            (isChecked) ? "1" : "0", null);
                    cloudUtils.setWifiOnlyMode(isChecked);
                }
            };

            setSwitchView(itemLayout, R.id.wifi_switch_btn, isWifiOnlyMode, R.string.access_via_wifi_only, R.string.access_via_wifi_only_subtext, listener);
        }
    }

    private void setSwitchView(View itemLayout, int switchId, boolean bBtnChecked, int titleId, int subTextId, OnCheckedChangeListener listener) {
        if (itemLayout != null) {
            final Switch switchBtn = (Switch) itemLayout.findViewById(switchId);
            if (switchBtn != null) {
                switchBtn.setChecked(bBtnChecked);
                switchBtn.setOnCheckedChangeListener(listener);
            }

            TextView title = (TextView) itemLayout.findViewById(R.id.title);
            title.setText(titleId);
            TextView subText = (TextView) itemLayout.findViewById(R.id.sub_text);
            subText.setText(subTextId);
            itemLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (switchBtn != null) {
                        switchBtn.setChecked(!switchBtn.isChecked());
                    }
                }
            });
        }
    }

    private void setAboutPage(View rootView) {
        View aboutContainer = rootView.findViewById(R.id.about_container);
        View aboutBadge = rootView.findViewById(R.id.about_page_badge);
        if(PreferenceUtils.getAvailAppUpdate(mContext)){
            aboutBadge.setVisibility(View.VISIBLE);
        }else{
            aboutBadge.setVisibility(View.GONE);
        }

        aboutContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS, SamsungAnalyticsLog.Event.ABOUT, null);
                enterMyFilesAbout();
            }
        });
    }

    private void enterMyFilesAbout() {
        Fragment aboutPageFragment = new AboutPageFragment();
        FragmentManager fm = getActivity().getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.settings_layout_container, aboutPageFragment);
        ft.addToBackStack(null);
        ft.commitAllowingStateLoss();
    }

    @Override
    public void onCloudInit() {
        Collection<AbsCloudImp> cloudImpList = mCloudMgr.getCloudImpList().values();
        for (AbsCloudImp cloudImp : cloudImpList) {
            updateLoginState(cloudImp.getCloudType());
        }
    }

    @Override
    public void onAccountChanged(CloudType cloudType) {
        updateLoginState(cloudType);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mCloudMgr.removeListener(this);
    }

    private void setCloudAccount(View rootView) {
        Collection<AbsCloudImp> cloudImpList = mCloudMgr.getCloudImpList().values();
        for (AbsCloudImp cloudImp : cloudImpList) {
            switch (cloudImp.getRequestCode()) {
                case CloudMgr.MYFILES_GOOGLEDRIVE_LOGIN:
                    setCloudAccountItem(rootView, cloudImp.getCloudType(), R.id.google_drive_account_stub, R.id.google_drive_account_view,
                            R.drawable.my_files_ic_drive, R.color.home_icon_google_drive_color, R.string.google_drive);
                    break;
                case CloudMgr.MYFILES_SAMSUNGDRIVE_LOGIN:
                    setCloudAccountItem(rootView, cloudImp.getCloudType(), R.id.samsung_drive_account_stub, R.id.samsung_drive_account_view,
                            R.drawable.my_files_ic_cloud, R.color.home_icon_samsung_drive_color, UiUtils.getSamsungDriveString());
                    break;
                default:
                    Log.e(this, "setCloudAccount() - Wrong cloud type : " + cloudImp.getCloudName());
                    break;
            }
        }
    }

    @Override
    public void onUpdateCheckResult(boolean hasMyFilesUpdate, boolean hasCloudUpdate) {
        MyFilesFacade.execSpinnerProgress(mProcessId, getActivity(), SpinnerProgressCmd.OperationProgress.DISMISS);
        Log.d(this, "update check result : MyFiles - " + hasMyFilesUpdate + ", Cloud - " + hasCloudUpdate);

        if (hasMyFilesUpdate || hasCloudUpdate) {
            UpdateDialogFragment.updateDialogShow(getFragmentManager(), hasCloudUpdate);
        } else {
            APKDownloadManager.getInstance(mContext.getApplicationContext()).setVersionChecking(false);
            setAccount(false, mSelectedCloudType);
        }
    }

    private void setCloudAccountItem(View rootView, final CloudType cloudType, int viewStubId, int viewId, int iconRes, int iconColorRes, int titleRes) {
        ViewStub accountStub = (ViewStub) rootView.findViewById(viewStubId);
        if (accountStub != null) {
            if (AppFeatures.isSupportSamsungDrive() && cloudType.equals(CloudType.GoogleDrive)) {
                accountStub.setLayoutResource(R.layout.home_list_item_divider);
            }
            accountStub.inflate();
        }

        View accountView = rootView.findViewById(viewId);
        ImageView cloudIcon = (ImageView) accountView.findViewById(R.id.home_list_item_thumbnail);
        cloudIcon.setImageResource(iconRes);
        cloudIcon.setColorFilter(ContextCompat.getColor(mContext, iconColorRes));

        TextView cloudTitle = (TextView) accountView.findViewById(R.id.home_list_item_text);
        cloudTitle.setText(titleRes);

        TextView cloudAccount = (TextView) accountView.findViewById(R.id.home_list_item_text_second);
        mAccountViewList.put(cloudType, cloudAccount);

        updateLoginState(cloudType);

        accountView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setAccount(true, cloudType);
            }
        });
    }

    private void _setAccount(CloudType cloudType) {
        if (!UiUtils.isNetworkOn(mContext)) {
            UnableToAccessServerDialogFragment accessDialogFragment = UnableToAccessServerDialogFragment.getInstance(R.string.unable_to_connect_network, this.getActivity());
            if (accessDialogFragment != null) {
                accessDialogFragment.showAllowingStateLoss(this.getFragmentManager(), UnableToAccessServerDialogFragment.NETWORK_WARNING);
            }
            return;
        }

        try {
            AccountManager accountMgr = AccountManager.get(mContext);
            Account[] accounts = accountMgr.getAccountsByType(mCloudMgr.getAccountType(cloudType));
            String cloudName = CloudFileRecord.getCloudName(cloudType);

            if (accounts.length == 0 || (accounts.length == 1 && !mCloudMgr.isSignedIn(cloudType))) {
                Intent intent = CloudGatewayStorageUtils.getInstance(mContext).createStorageSignInIntent(cloudName);
                startActivity(intent);
            } else {
                Bundle args = new Bundle();
                args.putString(SIGN_IN_CLOUD_TYPE, cloudName);
                Fragment selectAccountFragment = new SelectAccountFragment();
                selectAccountFragment.setArguments(args);
                FragmentManager fm = getActivity().getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.settings_layout_container, selectAccountFragment);
                ft.addToBackStack(null);
                ft.commitAllowingStateLoss();
            }
            SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.SETTINGS,
                    (cloudType == CloudType.SamsungDrive) ? SamsungAnalyticsLog.Event.SAMSUNG_CLOUD_DRIVE : SamsungAnalyticsLog.Event.GOOGLE_DRIVE, null);
        } catch (SecurityException e) {
            Log.e(this, "SecurityException:" + e.toString());
        }
    }

    private void setAccount(boolean needVersionCheck, CloudType cloudType) {
        if (!isAdded()) {
            Log.w(this, "setAccount - fragment is detached from activity, return");
            return;
        }
        mSelectedCloudType = cloudType;
        if (needVersionCheck) {
            Context appContext = mContext.getApplicationContext();
            if (APKDownloadManager.getInstance(appContext).getVersionChecking()) {
                int cloudResId = CloudFileRecord.getCloudStringId(cloudType);
                String cloudName = appContext.getResources().getString(cloudResId);
                String msg = appContext.getResources().getString(R.string.version_checking, cloudName);
                Toast.makeText(appContext, msg, Toast.LENGTH_LONG).show();
                Log.d(this, "Another window is checking version update");
                return;
            }
            if (!APKDownloadManager.getInstance(appContext).showUpdateDialog(mProcessId, getActivity(), getFragmentManager(), this)) {
                _setAccount(cloudType);
            }
        } else {
            _setAccount(cloudType);
        }
    }

    private void updateLoginState(CloudType cloudType) {
        TextView cloudAccount = (TextView) mAccountViewList.get(cloudType);
        if (cloudAccount != null) {
            AbsCloudImp updateCloud = mCloudMgr.getCloudImp(cloudType);
            if (TextUtils.isEmpty(updateCloud.getUserId())) {
                if (updateCloud.isSignedIn()) {
                    cloudAccount.setText(R.string.retrieving_account);
                } else {
                    int msgId;
                    switch (updateCloud.getCloudName()) {
                        case AppConstants.CloudType.GOOGLE_DRIVE:
                            msgId = R.string.cloud_google_drive_sign_in_mgs;
                            break;
                        case AppConstants.CloudType.SAMSUNG_DRIVE:
                            msgId = AppFeatures.IS_JPN ? R.string.cloud_galaxy_drive_sign_in_msg : R.string.cloud_samsung_drive_sign_in_msg;
                            break;
                        default:
                            msgId = R.string.cloud_sign_in_msg;
                            break;
                    }
                    cloudAccount.setText(msgId);
                }
            } else {
                cloudAccount.setText(updateCloud.getUserId());
            }
        }
    }

    private void changeSwitchButtonStateByIA(int id, boolean checked) {
        View view = getView();
        if (view != null) {
            Switch switchBtn = (Switch) view.findViewById(id);
            if (switchBtn != null) {
                switchBtn.setChecked(checked);
            }
        }
    }

    private void enterSubPage(Fragment fragment, String name) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.settings_layout_container, fragment);
        ft.addToBackStack(name);
        ft.commitAllowingStateLoss();
    }

    private boolean checkButtonState(int resId) {
        boolean bRet = false;
        View view = getView();
        if (view != null) {
            Switch switchBtn = (Switch) view.findViewById(resId);
            if (switchBtn != null && switchBtn.isChecked()) {
                bRet = true;
            }
        }
        return bRet;
    }
}
